package efg.tasks;

import java.util.List;
import java.util.Set;

import efg.RailwayElement;
import efg.SelfCheckableTask;
import efg.Track;
import efg.Train;

public class FrontalCollisionAvoidingTask extends SelfCheckableTask {

	private Track nextTrack;
	private Train train;
	private Set<Train> conflicts;

	public FrontalCollisionAvoidingTask(Track track, Train train,
			Set<Train> conficts) {
		super();
		assert (track != null && train != null && conficts != null && !conficts
				.isEmpty());
		assert(train.getRouteIds().contains(track.getId()));
		for (Train conflictTrain : conficts) {
			assert(conflictTrain.getRouteIds().contains(track.getId()));
		}
		this.nextTrack = track;
		this.train = train;
		this.conflicts = conficts;
	}

	@Override
	public Boolean canExecute() {
		assert(conflicts != null && ! conflicts.isEmpty());
		assert(train != null && nextTrack != null);
		for (Train conflictedTrain : conflicts) {
			RailwayElement currTrack = conflictedTrain.getCurrentPlace();
			if (!(currTrack instanceof Track)) {
				return false;
			}
			List<String> route = conflictedTrain.getRouteIds();
			Integer currIndex = route.indexOf(currTrack.getId());
			Integer targetIndex = route.indexOf(nextTrack.getId());
			if (currIndex <= targetIndex) {
				return false;
			}
		}
		return true;
	}

	@Override
	public void execute(Integer currentTime) {
		assert(canExecute());
		train.checkSwitchSchedule((Track) train.getCurrentPlace(), currentTime);
	}

}
